<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>欢迎登录开发喵网站</title>
    <link rel="stylesheet" href="/css/layui.css">
    <style>
        .demo-login-container {
            width: 320px;
            margin: 21px auto 0;
        }

        .demo-login-other .layui-icon {
            position: relative;
            display: inline-block;
            margin: 0 2px;
            top: 2px;
            font-size: 26px;
        }
    </style>
</head>
<body>
<!--用户名登录-->
<form class="layui-form" id="user-login">
    <div class="demo-login-container">
        <div class="layui-form-item">
            <div class="layui-input-wrap">
                <div class="layui-input-prefix">
                    <i class="layui-icon layui-icon-username"></i>
                </div>
                <input type="text" name="username" value="" lay-verify="required" placeholder="用户名"
                       lay-reqtext="请填写用户名" autocomplete="off" class="layui-input" lay-affix="clear">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-wrap">
                <div class="layui-input-prefix">
                    <i class="layui-icon layui-icon-password"></i>
                </div>
                <input type="password" name="password" value="" lay-verify="required" placeholder="密   码"
                       lay-reqtext="请填写密码" autocomplete="off" class="layui-input" lay-affix="eye">
            </div>
        </div>
        <!--验证码-->
        <!--第一次登录失败再显示出来-->
        <div class="layui-form-item" id="captcha">
            <div class="layui-row">
                <div class="layui-col-xs7">
                    <div class="layui-input-wrap">
                        <div class="layui-input-prefix">
                            <i class="layui-icon layui-icon-vercode"></i>
                        </div>
                        <input type="text" name="captcha" value="" placeholder="验证码"
                               autocomplete="off" class="layui-input" lay-affix="clear">
                    </div>
                </div>
                <div class="layui-col-xs5">
                    <div style="margin-left: 10px;">
                        <img src="/captcha"
                             onclick="this.src='/captcha?t='+ new Date().getTime();">
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <input type="checkbox" name="remember" lay-skin="primary" title="记住我">
            <a href="#forget" style="float: right; margin-top: 7px;">忘记密码？</a>
        </div>
        <div class="layui-form-item">
            <button class="layui-btn layui-btn-fluid" lay-submit lay-filter="login">登录</button>
        </div>
    </div>
</form>
<!--手机号登录表单-->
<form class="layui-form" id="phone-login">
    <div class="demo-login-container">
        <div class="layui-form-item">
            <div class="layui-input-wrap">
                <div class="layui-input-prefix">
                    <i class="layui-icon layui-icon-cellphone"></i>
                </div>
                <input type="text" name="phone" value="" lay-verify="required" placeholder="手机号"
                       lay-reqtext="请输入手机号" autocomplete="off" class="layui-input" lay-affix="clear"
                       oninput="handleInput(event)">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-row">
                <div class="layui-col-xs7">
                    <div class="layui-input-wrap">
                        <div class="layui-input-prefix">
                            <i class="layui-icon layui-icon-vercode"></i>
                        </div>
                        <input type="text" name="code" value="" placeholder="验证码"
                               autocomplete="off" class="layui-input" lay-affix="clear">
                    </div>
                </div>
                <div class="layui-col-xs5">
                    <div style="margin-left: 10px;">
                        <button type="button" id="phoneBtn" class="layui-btn layui-btn-disabled"
                                lay-on="getCode">获取验证码 <span class="layui-word-aux layui-font-green"
                                                                  id="countDown"></span>
                        </button>
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <input type="checkbox" name="remember" lay-skin="primary" title="记住密码">
            <a href="#forget" style="float: right; margin-top: 7px;">忘记密码？</a>
        </div>
        <div class="layui-form-item">
            <button class="layui-btn layui-btn-fluid" lay-submit lay-filter="phone-login">登录</button>
        </div>
    </div>
</form>
<!--邮箱登录表单-->
<form class="layui-form" id="email-login">
    <div class="demo-login-container">
        <div class="layui-form-item">
            <div class="layui-input-wrap">
                <div class="layui-input-prefix">
                    <i class="layui-icon layui-icon-username"></i>
                </div>
                <input type="text" name="username" value="" lay-verify="required" placeholder="用户名"
                       lay-reqtext="请填写用户名" autocomplete="off" class="layui-input" lay-affix="clear">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-wrap">
                <div class="layui-input-prefix">
                    <i class="layui-icon layui-icon-password"></i>
                </div>
                <input type="password" name="password" value="" lay-verify="required" placeholder="密   码"
                       lay-reqtext="请填写密码" autocomplete="off" class="layui-input" lay-affix="eye">
            </div>
        </div>
        <div class="layui-form-item">
            <input type="checkbox" name="remember" lay-skin="primary" title="记住密码">
            <a href="#forget" style="float: right; margin-top: 7px;">忘记密码？</a>
        </div>
        <div class="layui-form-item">
            <button class="layui-btn layui-btn-fluid" lay-submit lay-filter="login">登录</button>
        </div>
    </div>
</form>
<div class="demo-login-container">
    <div class="layui-form-item demo-login-other">
        <label>社交账号登录</label>
        <span style="padding: 0 21px 0 6px;">
                <a href="#" onclick="showPhone(event)"><i class="layui-icon layui-icon-cellphone"
                                                          style="color: #3492ed;"></i></a>
                <a href="#" onclick="showEmail(event)"><i class="layui-icon layui-icon-email"
                                                          style="color: #4daf29;"></i></a>
            </span>
        或 <a href="/register">注册帐号</a>
    </div>
</div>

<!-- 请勿在项目正式环境中引用该 layui.js 地址 -->
<script src="/js/layui.js"></script>
<script src="/js/axios.js"></script>
<script src="/js/jsencrypt.js"></script>
<script>
    let cookie = document.cookie
    console.log(cookie)

    function getCookie(cookie, k) {
        let cookies = cookie.split("; ")
        for (let i = 0; i < cookies.length; i ++) {
            let values = cookies[i].split("=")
            if (k === values[0]) {
                return values[1]
            }
        }
        return null
    }
    let token = getCookie(cookie, "login")
    if (token) {
        axios.get("/remember?token=" + token).then(res => {
            if (res.data.code === 1) {
                location.href = "/index"
            } else {
                location.href = "/login"
            }
        })
    }

    getCookie(cookie)
    let cap = document.querySelector("#captcha")
    let userForm = document.querySelector("#user-login")
    let phoneForm = document.querySelector("#phone-login")
    phoneForm.style.display = "none"
    let emailForm = document.querySelector("#email-login")
    emailForm.style.display = "none"
    let phoneBtn = document.querySelector("#phoneBtn")

    function handleInput(event) {
        if (event.target.value) {
            phoneBtn.classList.remove("layui-btn-disabled")
        } else {
            phoneBtn.classList.add("layui-btn-disabled")
        }
    }

    function showPhone(event) {
        event.preventDefault() // 阻止默认事件
        phoneForm.style.display = "block"
        userForm.style.display = "none"
        emailForm.style.display = "none"
    }

    function showEmail(event) {
        event.preventDefault()
        emailForm.style.display = "block"
        userForm.style.display = "none"
        phoneForm.style.display = "none"
    }

    // localStorage -- 存储到本地 setItem(key, value) 存储值 getItem(key) -- 获取存储的值
    // sessionStorage -- 存储到session中
    let item = sessionStorage.getItem("error_user"); // 获取session中是否有登录失败的记录
    if (item) {
        cap.style.display = "block" // 显示验证码
    } else {
        cap.style.display = "none"  // 隐藏验证码
    }
    layui.use("util", function () {
        let form = layui.form;
        let layer = layui.layer;
        let util = layui.util
        // 提交事件
        form.on('submit(login)', function (data) {
            console.log(data)
            getPublic(data)
            return false; // 阻止默认 form 跳转
        });


        // 处理手机号登录请求 submit(参数) 参数 --> lay-filter的属性值
        form.on('submit(phone-login)', function (data) {
            console.log(data.field)
            axios.post("/phoneLogin", {
                phone: data.field.phone,
                code: data.field.code
            }).then(res => {
                let resp = res.data
                console.log(resp)
                if (resp.code === 1) {
                    layer.msg(resp.msg, {icon: 6})
                    setTimeout(() => {
                        location.href = "/index"
                    }, 500)
                } else {
                    layer.msg(resp.msg, {icon: 5})
                    setTimeout(() => {
                        location.href = "/login"
                    }, 500)
                }
            })
            return false;
        })

        // util.on -- 批量注册事件
        util.on("lay-on", {
            // 发送验证码
            getCode: function () {
                phoneBtn.classList.add("layui-btn-disabled")
                let timeBox = document.querySelector("#countDown")
                timeBox.innerText = 60
                let timer = setInterval(() => {
                    // 倒计时
                    let time = timeBox.innerText
                    if (time == 0) {
                        // 如果变化成 0 按钮恢复可以使用，清除计时器
                        phoneBtn.classList.remove("layui-btn-disabled")
                        clearInterval(timer)
                    } else {
                        timeBox.innerText = parseInt(time) - 1
                    }
                }, 1000)
                let phone = document.querySelector("[name='phone']").value
                console.log(phone)
                axios.get("/sendMessage?phone=" + phone).then(res => {
                    let resp = res.data
                    if (resp.code === 1) {
                        layer.msg(resp.msg, {icon: 6})
                    } else {
                        layer.msg(resp.msg, {icon: 5})
                    }
                })
            }
        })
    });

    function getPublic(data) {
        axios.get("/getPublicKey").then(res => {
            let resp = res.data
            if (resp.code === 1) {
                // 获取秘钥成功
                let uuid = resp.data.uuid
                let key = resp.data.publicKey
                let jsencrypt = new JSEncrypt()
                // 设置公钥
                jsencrypt.setKey(key)
                let field = data.field; // 获取表单字段值
                let password = jsencrypt.encrypt(field.password)
                let username = jsencrypt.encrypt(field.username)
                let user = {
                    username: username,
                    password: password,
                    uuid: uuid,
                    captcha: field.captcha,
                    hasCaptcha: item ? true : false, // 本次请求是否携带验证码
                    remember: field.remember === "on"
                }
                login(user, field)
            }
        })
    }

    function login(user, field) {
        axios.post("/user/login", user).then(res => {
            let response = res.data
            if (response.code === 1) {
                // 登录成功，将登录成功的用户信息转换成json字符串存储到sessionStorage
                sessionStorage.setItem("loginUser", JSON.stringify(response.data))
                sessionStorage.removeItem("error_user") // 移除存储的失败标记
                layer.msg(response.msg, {icon: 6}, function () {
                });
                setTimeout(() => {
                    location.href = "/index"
                }, 500)
            } else {
                // 登录失败 sessionStorage 存储一个标志
                sessionStorage.setItem("error_user", field.username)
                layer.msg(response.msg, {icon: 0}, function () {
                });
                setTimeout(() => {
                    if (response.code === 401) { // 非法的操作
                        location.href = "/error"
                    } else {
                        location.href = "/login"
                    }
                }, 500)
            }
        })
    }


</script>
</body>
</html>